<?php
// This file is used to insert new artifacts (as passed by post vars)
// TODO - check user permissions
// TODO - once Elgg provides an easy way to load session information w/o the entire lib,
//          remove the large includes.php file, as none of the rest depends on libs outside
//          of mysql support & generic php.

// Headers are needed to force IE to not cache results.
header('Cache-Control: no-cache, no-store, must-revalidate'); //HTTP/1.1
header('Expires: Sun, 01 Jul 2005 00:00:00 GMT');
header('Pragma: no-cache'); //HTTP/1.0

require_once('../../../includes.php');
require_once("../view/page.php");
require_once("../view/PageEditor.php");

require_once("../model/resource.php");
require_once("../model/artifact.php");
require_once("../model/decoration.php");
require_once("../model/file.php");

if ( !( isset( $_POST['key'] ) AND isset( $_POST['page_ident'] ) ))
    trigger_error('Need key, and page_ident for artifact_insert.php', E_USER_ERROR);

// Retrieve a single artifact in rich editor mode.

$key = $_POST['key'];
$page_ident = intval( $_POST['page_ident'] );

// Validate permissions
$page = folio_page::SelectWherePageIdent( $page_ident );

if ( !$page->Permission('update') ) {
    trigger_error('You do not have permission to edit this page', E_USER_ERROR);
}

$page_owner = $page->user_ident;

// Following validates the key values, dieing if invalid params.
$KeyArray = folio_resource::decodeKey( $key );

// Retrieve the resource we want to turn into an artifact.
$resources = folio_resource::SelectWhereKey( $key );

// Test to make sure this is a valid set of resources
if ( count($resources) == 0 )
    trigger_error('Invalid resource key: ' . $key . ' passed to artifact_insert.php', E_USER_ERROR);

// Create an artifact based off of the resource.
$artifacts = folio_artifact::CreateArtifactsFromResources( $resources, $page_owner, $page_ident );

if ( count($artifacts)==0 )
    trigger_error('Invalid resource key: ' . $key . ' passed to artifact_insert.php', E_USER_ERROR);

// Load artifact(s) html into the page, along with the js to be executed.
$html = folio_PageEditor::Add( $artifacts ) ;

echo $html;

?>
